﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace System
{
    public static partial class ObjectExtension
    {
        /// <summary>
        /// 从 lambda 表达式中获取模型名称
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <param name="expression"></param>
        /// <returns></returns>
        public static string GetExpressionText<T>(this T obj, Expression<Func<T, object>> expression)
        {
            return expression.GetExpressionText();
        }

        /// <summary>
        /// 返回ChineseDescriptionAttribute，DisplayAttribute，Name中第一个不为空的
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <param name="expression"></param>
        /// <returns></returns>
        public static string GetChineseDescription<T>(this T obj, Expression<Func<T, object>> expression)
        {
            var memberInfo = expression.FindProperty();
            var chineseDescription = memberInfo.GetCustomAttributes<ChineseDescriptionAttribute>(false)
                                               .OrderByDescending(x => x.Order)
                                               .FirstOrDefault();
            if (chineseDescription != null)
            {
                return chineseDescription.Text;
            }
            var display = memberInfo.GetCustomAttributes<DisplayAttribute>(false)
                                    .OrderByDescending(x => x.Order)
                                    .FirstOrDefault();
            if (display != null)
            {
                return display.Name;
            }
            return memberInfo.Name;
        }
    }
}
